package com.study.optional;

import org.junit.Test;

import java.util.Optional;

/**
 * @program: java8
 * @description: Optional 类
 * @author: yangyb
 * @create: 2021-11-14 23:08
 **/
public class OptionalTest {
    /**
     * @Description: - Optional.of(T t)--创建一个Optional 实例，t必须非空；
     * - Optional.empty()--创建一个空的Optional实例
     * - Optional.ofNullable(T t):t可以为null
     * @Param: []
     * @return:
     */
    @Test
    public void test1() {
        Girl girl = new Girl();
        //of(T t)：保证t是非空的；
        Optional<Girl> optional = Optional.of(girl);
    }

    @Test
    public void test2() {
        Girl girl = new Girl();
        //girl=null;
        girl = null;
        //ofNullable(T t):t 可以为null
        Optional<Girl> optional = Optional.ofNullable(girl);
        System.out.println(optional);
        //orElse(T t1)：如果当前的Optional内部封装的t是非空的，则返回内部的t
        //如果内部封装的t是空的，否则返回orElse（）方法中参数t1
        Girl girl1 = optional.orElse(new Girl("杨幂"));
        System.out.println(girl1);


    }

    public String getGirlName(Boy boy) {
        return boy.getGirl().getName();
    }

    @Test
    public void test3() {
        Boy boy = new Boy();
        String girlName = getGirlName1(boy);
        System.out.println(girlName);
    }

    /**
     * @Description: 普通优化后
     * @Param: [boy]
     * @return:
     */
    public String getGirlName1(Boy boy) {
        if (boy != null) {
            Girl girl = boy.getGirl();
            if (girl != null) {
                return boy.getGirl().getName();
            }
        }
        return null;
    }

    /**
     * @Description: 使用Optional类
     * @Param: [boy]
     * @return:
     */
    public String getGirlName2(Boy boy) {
        Optional<Boy> optionalBoy = Optional.ofNullable(boy);
        Boy boy1 = optionalBoy.orElse(new Boy(new Girl("迪丽热巴")));
        Girl girl = boy1.getGirl();
        Optional.ofNullable(girl).ifPresent(e -> System.out.println(e.getName()));
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        Girl girl1 = optionalGirl.orElse(new Girl("古力娜扎"));
        return girl1.getName();

    }

    @Test
    public void test4() {
        //Boy boy = new Boy();
        Boy boy = null;
        //Boy boy = new Boy(new Girl("欧阳娜娜"));
        String girlName2 = getGirlName2(boy);
        System.out.println(girlName2);
    }

}
